package com.zy.service.bs.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Example;

import com.zy.dao.bs.LableTypeDao;
import com.zy.entity.bs.LableType;
import com.zy.entity.enums.StatusEnum;
import com.zy.pojo.exceptions.ServiceException;
import com.zy.pojo.query.bs.LableTypeQuery;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.LableTypeService;
import com.zy.utils.DateUtil;

@Service("lableTypeService")
public class LableTypeServiceImpl extends BaseServiceImpl<LableType> implements LableTypeService {

	@Autowired
	private LableTypeDao lableTypeDao;

	@Override
	public PageVo pageLableType(LableTypeQuery lableTypeQuery, Integer start, Integer limit) {
		return new PageVo(start, limit, this.lableTypeDao.countLableType(lableTypeQuery), this.lableTypeDao.listLableType(lableTypeQuery, start, limit));
	}

	@Override
	public void saveLableType(LableType lableType) {
		lableType.setId(null);
		existsName(lableType);
		long time = DateUtil.getTime();
		lableType.setCreateTime(time);
		lableType.setModifyTime(time);
		lableType.setStatus(StatusEnum.NORMAL.getValue());
		this.lableTypeDao.save(lableType);
	}
	
	@Override
	public void updateLableType(LableType lableType) {
		existsName(lableType);
		lableType.setModifyTime(DateUtil.getTime());
		this.lableTypeDao.updateByPrimaryKeySelective(lableType);
	}

	@Override
	public void removeLableType(long id) {
		try {
			this.lableTypeDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			LableType lableType = new LableType();
			lableType.setId(id);
			lableType.setModifyTime(DateUtil.getTime());
			lableType.setStatus(StatusEnum.DELETE.getValue());
			this.lableTypeDao.updateByPrimaryKeySelective(lableType);
		}
	}

	@Override
	public void recover(long id) {
		LableType lableType = new LableType();
		lableType.setId(id);
		lableType.setModifyTime(DateUtil.getTime());
		lableType.setStatus(StatusEnum.NORMAL.getValue());
		this.lableTypeDao.updateByPrimaryKeySelective(lableType);
	}

	private void existsName(LableType lableType) {
		Example ex = new Example(LableType.class);
		Example.Criteria cr = ex.createCriteria();
		cr.andEqualTo("lableName", lableType.getLableName());
		LableType pojo = lableTypeDao.getByExample(ex);
		if (pojo != null && !pojo.getId().equals(lableType.getId())) {
			throw new ServiceException(lableType.getLableName()+"重复类型名");
		}

	}

}
